//
//  LGLoginViewController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/2/13.
//

#import "LGLoginViewController.h"
//注册账号
#import "LGRegistViewController.h"
//验证手机号
#import "LGCheckPhoneController.h"
//设置密码
#import "LGSetPasswordController.h"
#import "LGSetNewPasswordController.h"

#import "LGGetWebViewController.h"

//协议弹框
#import "LGProtocolAlertView.h"

#import "LGTabBarViewController.h"

#import "LGAgreementAlertView.h"

//输入栏
#import "LGAccountInputView.h"
#import "LGDeviceID.h"

#import <ImSDK_Plus/ImSDK_Plus.h>
#import "TUILogin.h"
@interface LGLoginViewController ()<UITextFieldDelegate>
/**   */
//@property (nonatomic , strong)CAGradientLayer *gradLayer;
/**   */
@property (nonatomic , strong)UIImageView *bgImageView;
/**   */
@property (nonatomic , strong)UIButton *titleBtn;
/**   */
@property (nonatomic , strong)UILabel *subTitle;
/**   */
@property (nonatomic , strong)LGAccountInputView *topView;
/**   */
@property (nonatomic , strong)LGAccountInputView *bottomView;
/**   */
@property (nonatomic , strong)UIButton *forgetBtn;
/**   */
@property (nonatomic , strong)UIButton *loginBtn;
/**   */
@property (nonatomic , strong)UIButton *typeBtn;
/**   */
@property (nonatomic , strong)UIButton *agreeBtn;
/**   */
@property (nonatomic , strong)UILabel *agreeLabel;
/**   */
@property (nonatomic , copy)NSString *agreeUrl;
/**   */
@property (nonatomic , copy)NSString *policyUrl;
/**   */
@property (nonatomic , strong)NSTimer *timer;
/**   */
@property (nonatomic , assign)NSInteger seconds;

@end

@implementation LGLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.seconds = 60;
    [self createSubView];
    [self showAgreementView];
//    [self requestAppData];
}

-(void)requestAppData{
    [RequestUtil withPOST:@"/doctor/user.Auth/appinfo" parameters:@{} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if (code == 200) {
            
        }
    } error:^(NSError *error) {
        
    }];
}

-(void)setType:(NSString *)type{
    _type = type;
}

-(void)showAgreementView{
    NSString *showGuide = [[NSUserDefaults standardUserDefaults] objectForKey:@"showGuide"];
    if(!showGuide || showGuide.length ==0 ||![showGuide isEqualToString:@"Y"]){
        LGAgreementAlertView *view = [[LGAgreementAlertView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
        __weak typeof(self) weakSelf = self;
        view.agreementAlertAction = ^(NSString * _Nonnull action) {
            if([action isEqualToString:@"continue"]){
                //同意并继续
                [[NSUserDefaults standardUserDefaults] setValue:@"Y" forKey:@"showGuide"];
                weakSelf.agreeBtn.selected = YES;
                
            }else if ([action isEqualToString:@"agreement"]){
                //用户协议
                LGGetWebViewController *controller = [[LGGetWebViewController alloc]init];
                controller.urlStr = AgreementLink;
                controller.title = @"用户协议";
                [self.navigationController pushViewController:controller animated:YES];
                
            }else if ([action isEqualToString:@"privacy"]){
                //隐私协议
                LGGetWebViewController *controller = [[LGGetWebViewController alloc]init];
                controller.urlStr = PrivacyLink;
                controller.title = @"隐私政策";
                [self.navigationController pushViewController:controller animated:YES];
            }
        };
        [[UIApplication sharedApplication].keyWindow addSubview:view];
    }
    
}

//获取验证码
-(void)getSmsCodeAction:(UIButton *)sender{
    NSString *phoneNum = [self.topView.contenTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if([self checkTelNumber:phoneNum] == NO){
        [TooltipView showMessage:@"请输入正确的手机号" offset:0];
        return;
    }
    [RequestUtil withPOST:@"/doctor/user.auth/sendSmsCode" parameters:@{@"mobile":phoneNum} withSign:NO success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.seconds = 60;
            [self.timer invalidate];
            self.timer = nil;
            self.bottomView.actionBtn.selected = YES;
            self.bottomView.actionBtn.userInteractionEnabled = NO;
            [self.bottomView.actionBtn setTitle:[NSString stringWithFormat:@"重新发送(%ld)",self.seconds] forState:UIControlStateNormal];
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        
    }];
}

//验证码倒计时
-(void)countDownAction{
    self.seconds--;
    [self.bottomView.actionBtn setTitle:[NSString stringWithFormat:@"重新发送(%ld)",self.seconds] forState:UIControlStateNormal];
    if (self.seconds == 0) {
        self.bottomView.actionBtn.selected = NO;
        self.bottomView.actionBtn.userInteractionEnabled = YES;
        [self.bottomView.actionBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.timer invalidate];
        self.timer = nil;
    }
}

//忘记密码
-(void)forgetPasswordAction{
    NSString *phone = [self.topView.contenTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if([self checkTelNumber:phone]){
        LGCheckPhoneController *controller = [[LGCheckPhoneController alloc]init];
        controller.phone = phone;
        controller.backVC = self;
        [self.navigationController pushViewController:controller animated:YES];
    }else{
        [TooltipView showMessage:@"请输入正确的手机号" offset:0];
    }
    
}

//点击登录
-(void)loginBtnAction{
    if (self.agreeBtn.selected == YES) {
        NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
        NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        NSString *phone = [self.topView.contenTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithDictionary:@{@"username":phone,@"push_id":XGToken,@"client":@"app",@"client_version":appVersion,@"os":@"iOS",@"os_version":systemVersion,@"device_model":[LGDeviceID getDeviceModel],@"device_id":[LGDeviceID getIOSUUID]}];
        if([self.type isEqualToString:@"code"]){
            [tempDic setValue:self.bottomView.contenTF.text forKey:@"code"];
            [tempDic setValue:@"mobile" forKey:@"type"];
        }else{
            [tempDic setValue:self.bottomView.contenTF.text forKey:@"password"];
            [tempDic setValue:@"其他" forKey:@"type"];
        }
        [RequestUtil withPOST:@"/doctor/user.auth/login" parameters:tempDic withSign:NO success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setValue:LGNSString(returnData[@"user_id"]) forKey:@"userid"];
                [userDefaults setValue:LGNSString(returnData[@"mobiletoken"]) forKey:@"utoken"];
                [userDefaults setValue:LGNSString(returnData[@"username"]) forKey:@"phone"];
                [userDefaults setValue:@"Y" forKey:@"islogin"];
                [userDefaults synchronize];
                //登录腾讯云
                [LGLoginManager loginTencentCloud];
                [UIApplication sharedApplication].keyWindow.rootViewController = [[LGTabBarViewController alloc]init];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            [TooltipView showMessage:LGErrorMessage offset:0];
        }];
    }else{
        //弹出协议弹框
        LGProtocolAlertView *alertView = [[LGProtocolAlertView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
        __weak typeof(self) weakSelf = self;
        alertView.agreementAlertAction = ^(NSString * _Nonnull action) {
            if([action isEqualToString:@"continue"]){
                //同意
                weakSelf.agreeBtn.selected = YES;
                [weakSelf loginBtnAction];
                
            }else if ([action isEqualToString:@"agreement"]){
                //用户协议
                LGGetWebViewController *controller = [[LGGetWebViewController alloc]init];
                controller.urlStr = AgreementLink;
                controller.title = @"用户协议";
                [self.navigationController pushViewController:controller animated:YES];
                
            }else if ([action isEqualToString:@"privacy"]){
                //隐私政策
                LGGetWebViewController *controller = [[LGGetWebViewController alloc]init];
                controller.urlStr = PrivacyLink;
                controller.title = @"隐私政策";
                [self.navigationController pushViewController:controller animated:YES];
            }
        };
        [self.view.window addSubview:alertView];
    }
}

//同意协议
-(void)agreeBtnAction:(UIButton *)sender{
    sender.selected = !sender.selected;
}

//使用协议和隐私政策
-(void)agreementTapAction:(UITapGestureRecognizer *)sender{
    if (self.agreeUrl.length == 0) {
//        return;
    }
    CGPoint point = [sender locationInView:self.agreeLabel];
    NSString *url = @"";
    NSString *title = @"";
    if (isPad) {
        if (point.x > 100 && point.x < 190) {
            //使用协议
            url = AgreementLink;
            title = @"用户协议";
            
        }else if(point.x > 220 && point.x < 300){
            //隐私协议
            url = PrivacyLink;
            title = @"隐私权政策";
        }else{
            url = @"";
            [self agreeBtnAction:self.agreeBtn];
        }
    }else{
//        UIView *redView = [[UIView alloc]initWithFrame:CGRectMake(90, 0, 70, 20)];
//        redView.backgroundColor = [UIColor redColor];
//        [self.agreeLabel addSubview:redView];
        if (point.x > 90 && point.x < 160) {
            //使用协议
            url = AgreementLink;
            title = @"用户协议";
        }else if(point.x > 190 && point.x < 260){
            //隐私协议
            url = PrivacyLink;
            title = @"隐私权政策";
        }else{
            url = @"";
            [self agreeBtnAction:self.agreeBtn];
        }
    }
    
    if (url.length>0) {
        LGGetWebViewController *controller = [[LGGetWebViewController alloc]init];
        controller.urlStr = url;
        controller.title = title;
        controller.isPresent = YES;
        [self.navigationController pushViewController:controller animated:YES];
    }
}

//切换登录方式
-(void)changeLoginTypeAction{
    if([kIsFree isEqualToString:@"Y"]){
        //注册账号
        LGRegistViewController *controller = [[LGRegistViewController alloc]init];
        [self.navigationController pushViewController:controller animated:YES];
        
    }else{
        if ([self.type isEqualToString:@"code"]) {
            LGLoginViewController *controller = [[LGLoginViewController alloc]init];
            controller.type = @"password";
            [self.navigationController pushViewController:controller animated:YES];
        }else{
            if(self.navigationController.childViewControllers.count>1){
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                LGLoginViewController *controller = [[LGLoginViewController alloc]init];
                controller.type = @"code";
                [self.navigationController pushViewController:controller animated:YES];
            }
        }
    }
}


-(void)textFieldDidEndEditing:(UITextField *)textField{
    NSString *phone = [self.topView.contenTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *code = self.bottomView.contenTF.text;
    if([self.type isEqualToString:@"code"]){
        if(phone.length == 11 && code.length >0){
            self.loginBtn.selected = YES;
            self.loginBtn.userInteractionEnabled = YES;
        }else{
            self.loginBtn.selected = NO;
            self.loginBtn.userInteractionEnabled = NO;
        }
    }else{
        if(phone.length == 11 && code.length >=6){
            self.loginBtn.selected = YES;
            self.loginBtn.userInteractionEnabled = YES;
        }else{
            self.loginBtn.selected = NO;
            self.loginBtn.userInteractionEnabled = NO;
        }
    }
    
}

//判断手机格式
- (BOOL)checkTelNumber:(NSString *)telNumber{
    NSString *pattern = @"^1+[0123456789]+\\d{9}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    BOOL isMatch = [pred evaluateWithObject:telNumber];
    return isMatch;
}


#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    self.gradientLayer.hidden = YES;
    self.fd_prefersNavigationBarHidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bgImageView];
    [self.view addSubview:self.titleBtn];
    [self.view addSubview:self.subTitle];
    [self.view addSubview:self.topView];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.loginBtn];
    [self.view addSubview:self.agreeLabel];
    [self.view addSubview:self.agreeBtn];
    [self.view addSubview:self.typeBtn];
    self.type = (self.type && self.type.length>0)?self.type:@"code";
    self.type = [kIsFree isEqualToString:@"Y"]?@"password":self.type;
    if([self.type isEqualToString:@"code"]){
        //验证码登录
        self.bottomView.type = @"code";
        [self.typeBtn setTitle:@"密码登录" forState:UIControlStateNormal];
        [self.typeBtn setImage:[UIImage imageNamed:@"passwordLogin"] forState:UIControlStateNormal];
        [self.typeBtn setImage:[UIImage imageNamed:@"passwordLogin"] forState:UIControlStateHighlighted];
        [self.bottomView.actionBtn addTarget:self action:@selector(getSmsCodeAction:) forControlEvents:UIControlEventTouchUpInside];
    }else{
        //密码登录
        self.bottomView.type = @"password";
        [self.view addSubview:self.forgetBtn];
        NSString *typeTitle = [kIsFree isEqualToString:@"Y"]?@"注册账号":@"验证码登录";
        [self.typeBtn setTitle:typeTitle forState:UIControlStateNormal];
        [self.typeBtn setImage:[UIImage imageNamed:@"smsLogin"] forState:UIControlStateNormal];
        [self.typeBtn setImage:[UIImage imageNamed:@"smsLogin"] forState:UIControlStateHighlighted];
    }
    [self.typeBtn setButtonInsetsStyle:LGButtonInsetsStyleTop marginSpace:7];
}

-(UIImageView *)bgImageView{
    if(!_bgImageView){
        _bgImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"登录-背景"]];
        _bgImageView.frame = CGRectMake(0, 0, Screen_W, viewPix(396));
        _bgImageView.userInteractionEnabled = YES;
    }
    return _bgImageView;
}

-(UIButton *)titleBtn{
    if(!_titleBtn){
        _titleBtn = [UIButton buttonWithTitle:AppTitle titleFont:LGFontWeight(24, UIFontWeightSemibold) textColor:@"#333333" imageName:loginLogo];
        _titleBtn.frame = CGRectMake(viewPix(28), topBarHeight+viewPix(6), Screen_W-viewPix(56), viewPix(40));
        _titleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_titleBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 7, 0, 0)];
    }
    return _titleBtn;
}

-(UILabel *)subTitle{
    if(!_subTitle){
        NSString *title = [AppTitle isEqualToString:@"圆荷健康"]?@"圆荷健康医助平台":@"心内科医护平台";
        _subTitle = [UILabel lableWithText:title colorString:@"#999999" textFont:LGFont(16) textAlignment:NSTextAlignmentLeft lines:1];
        _subTitle.frame = CGRectMake(viewPix(28), kMaxY(self.titleBtn.frame)+viewPix(12), viewPix(200), viewPix(25));
    }
    return _subTitle;
}

-(LGAccountInputView *)topView{
    if(!_topView){
        _topView = [[LGAccountInputView alloc] initWithFrame:CGRectMake(viewPix(16), kMaxY(self.subTitle.frame)+viewPix(65), Screen_W-viewPix(32), viewPix(56))];
        _bottomView.contenTF.delegate = self;
        _topView.type = @"phone";
    }
    return _topView;
}

-(LGAccountInputView *)bottomView{
    if(!_bottomView){
        _bottomView = [[LGAccountInputView alloc] initWithFrame:CGRectMake(viewPix(16), kMaxY(self.topView.frame)+viewPix(16), Screen_W-viewPix(32), viewPix(56))];
        _bottomView.contenTF.delegate = self;
    }
    return _bottomView;
}


-(UIButton *)forgetBtn{
    if(!_forgetBtn){
        _forgetBtn = [UIButton buttonWithTitle:@"忘记密码？" titleFont:LGFont(12) textColor:@"#429BFF" imageName:@""];
        _forgetBtn.frame = CGRectMake(Screen_W-viewPix(84)-iPadMargin(5), kMaxY(self.bottomView.frame)+viewPix(7), viewPix(64)+iPadMargin(5), viewPix(30));
        _forgetBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_forgetBtn addTarget:self action:@selector(forgetPasswordAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _forgetBtn;
}


-(UIButton *)loginBtn{
    if(!_loginBtn){
        _loginBtn = [UIButton buttonWithTitle:@"登录" titleFont:LGFontWeight(16, UIFontWeightMedium) textColor:@"#FFFFFF" imageName:@""];
        _loginBtn.frame = CGRectMake(viewPix(16), Screen_H-viewPix(228)-iPhoneXMargin(25), Screen_W-viewPix(32), viewPix(48));
        [_loginBtn setBackgroundColor:[UIColor colorWithString:@"#E0E0E0"] forState:UIControlStateNormal];
        [_loginBtn setBackgroundColor:[UIColor colorWithString:@"#2E8FFF"] forState:UIControlStateSelected];
        _loginBtn.userInteractionEnabled = NO;
        _loginBtn.cornerRidus = 10;
        [_loginBtn addTarget:self action:@selector(loginBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginBtn;
}


-(UILabel *)agreeLabel{
    if(!_agreeLabel){
        NSString *content = @"我已阅读并同意《用户协议》以及《隐私政策》";
        _agreeLabel = [UILabel lableWithText:content colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        _agreeLabel.frame = CGRectMake((Screen_W-260-iPadMargin(45))/2.0, kMaxY(self.loginBtn.frame)+viewPix(15), 260+iPadMargin(45), viewPix(20));
        NSMutableAttributedString *attributStr = [[NSMutableAttributedString alloc]initWithString:content];
        [attributStr addAttributes:@{NSForegroundColorAttributeName:LGStringColor(@"#3692FF")} range:NSMakeRange(7, 6)];
        [attributStr addAttributes:@{NSForegroundColorAttributeName:LGStringColor(@"#3692FF")} range:NSMakeRange(15, 6)];
        _agreeLabel.attributedText = attributStr;
        [_agreeLabel addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(agreementTapAction:)]];
        _agreeLabel.userInteractionEnabled = YES;
    }
    return _agreeLabel;
}

-(UIButton *)agreeBtn{
    if(!_agreeBtn){
        _agreeBtn = [UIButton buttonWithImage:@"unselect" selectImage:@"selected"];
        _agreeBtn.frame = CGRectMake(kMinX(self.agreeLabel.frame)-viewPix(25), kMinY(self.agreeLabel.frame)-viewPix(5), viewPix(30), viewPix(30));
        [_agreeBtn addTarget:self action:@selector(agreeBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _agreeBtn;
}

-(UIButton *)typeBtn{
    if(!_typeBtn){
        _typeBtn = [UIButton buttonWithTitle:@"密码登录" titleFont:LGFont(12) textColor:@"#666666" imageName:@"passwordLogin"];
        _typeBtn.frame = CGRectMake((Screen_W-viewPix(80))/2.0, kMaxY(self.agreeLabel.frame)+viewPix(45), viewPix(80), viewPix(65));
        [_typeBtn setButtonInsetsStyle:LGButtonInsetsStyleTop marginSpace:7];
        [_typeBtn addTarget:self action:@selector(changeLoginTypeAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _typeBtn;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
